import { Modal, Input, useNotification } from '@web3uikit/core'
import { useState } from 'react'
import { useWeb3Contract } from 'react-moralis'
import NFTSHOPAbi from '../constant/NFTSHOP.json'
import { ethers } from 'ethers'
import React from 'react'

export default function UpdateListingModal({ nftAddress, tokenId, isVisible, NFTShopAddress, onClose }) {
  const dispatch = useNotification()

  const [priceToUpdateListingWith, setPriceToUpdateListingWith] = useState(0)

  const handleUpdateListingSuccess = () => {
    dispatch({
      type: 'success',
      message: 'listing updated',
      title: 'Listing updated - please refresh (and move blocks)',
      position: 'topR'
    })
    onClose && onClose()

    setPriceToUpdateListingWith(0)
  }

  const { runContractFunction: updateListing } = useWeb3Contract({
    abi: NFTSHOPAbi,
    contractAddress: NFTShopAddress,
    functionName: 'updateNftState',
    params: {
      nftAddress: nftAddress,
      tokenId: tokenId,

      newPrice: ethers.utils.parseEther(priceToUpdateListingWith.toString() || '0')
    }
  })

  return (
    <Modal
      isVisible={isVisible}
      onCancel={onClose}
      onCloseButtonPressed={onClose}
      onOk={() => {
        updateListing({
          onError: error => {
            console.log(error)
          },
          onSuccess: handleUpdateListingSuccess
        })
      }}
    >
      <Input
        label="Update listing price in L1 Currency (ETH)"
        name="New listing price"
        type="number"
        onChange={event => {
          setPriceToUpdateListingWith(Number.parseInt(event.target.value))
        }}
      />
    </Modal>
  )
}
